i18n+ Next.js国际化

i18n+ Next.js

1. i18n.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import LanguageDetector from "i18next-browser-languagedetector";
import i18n from "i18next";
import getConfig from "next/config";
import { initReactI18next } from "react-i18next";
import enUsTrans from "./locales/en-US.json";
import zhCnTrans from "./locales/zh-CN.json";

// 通过配置文件获取默认语言
const defalutLanguage = getConfig().publicRuntimeConfig.language
? getConfig().publicRuntimeConfig.language
: "zh_CN";

i18n
.use(LanguageDetector) // 嗅探当前浏览器语言
.use(initReactI18next) // init i18next
.init({
// 引入资源文件
resources: {
zh_CN: {
translation: zhCnTrans
},
en_US: {
translation: enUsTrans
}
},
lng: defalutLanguage, // 选择默认语言,选择内容为上述配置中的key,即en/zh 如果开启了 LanguageDetector 则可以不用默认语言,会自动匹配未嗅探到的语言
fallbackLng: "zh_CN", // 未找到对应语言包时候的失败语言包
debug: false,
interpolation: {
escapeValue: false // not needed for react as it escapes by default
}
});

export default i18n;

2. package.json

1
2
3
"i18next": "^20.3.5",
"i18next-browser-languagedetector": "^6.1.2",
"react-i18next": "^11.11.3",

3. 多语言文件.json

image-20230505201800541

4. 匹配现有项目的UI库多语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 匹配antd
import zh_CN from "antd/lib/locale-provider/zh_CN";
import en_US from "antd/lib/locale-provider/en_US";

export const getMatchedLocal = (language: string) => {
let target = zh_CN; // 默认语言
switch (language) {
case "zh_CN":
target = zh_CN;
break;
case "en_US":
target = en_US;
break;
default:
break;
}

return target;
};

5. 注入ConfigProvider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { ConfigProvider } from "antd";
import { useTranslation } from "react-i18next";
import "../i18n";

const APP = () => {
const { t, i18n } = useTranslation();

return(
<ConfigProvider locale={getMatchedLocal(i18n.language)}>
<Button onClick={() => i18n.changeLanguage('zh-CN')}>{t('切换到中文')}</Button>

{t("title")}
</ConfigProvider>
)
}
感谢你的打赏哦!